<template>
    <div>
        <el-row>
            <el-col :span="24">
                <div class="grid-content bg-purple-dark">
                    <!--&lt;!&ndash;添加资料&ndash;&gt;-->
                    <!--<el-popover ref="popover1" placement="right-end" title="提示" width="200" trigger="hover"-->
                    <!--content="课件详情里有所有的小节">-->
                    <!--</el-popover>-->
                    <el-button type="primary" @click="resourceAdd">添加资料</el-button>
                </div>
            </el-col>
        </el-row>

        <el-table :data="tableData" border>

            <el-table-column label="上传时间" prop="resourceAddTimeStr">
            </el-table-column>

            <!--<el-table-column label="资料名称" prop="resourceName">-->
            <!--</el-table-column>-->

            <el-table-column label="资料标题" prop="resourceTitle">
            </el-table-column>

            <el-table-column label="资料描述" prop="resourceDescribe">
            </el-table-column>

            <el-table-column label="资料大小(KB)" prop="resourceSize">
            </el-table-column>

            <el-table-column label="文件名" prop="resourceName">
            </el-table-column>

            <el-table-column label="下载次数" sortable prop="resourceFrequence">
                <!--<template scope="scope">-->
                <!--<i class="el-icon-star-on"></i>-->
                <!--&lt;!&ndash;<span style="margin-left: 10px">{{ scope.row.resourceFrequence }}</span>次&ndash;&gt;-->
                <!--</template>-->
            </el-table-column>

            <el-table-column label="操作">
                <template scope="scope">
                    <el-button size="small" @click="downResource(scope.row.resourceId)" type="success">下载</el-button>
                    <el-button size="small" type="info" @click="handleEdit(scope.$index, scope.row)">更新</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删 除</el-button>
                </template>
            </el-table-column>
        </el-table>


        <!--新增界面-->
        <el-dialog title="添加资料" v-model="addFormVisible" :close-on-click-modal="false">

            <el-form :model="addForm" label-width="100px" ref="addForm" :rules="addRules">
                <el-form-item label="标题：" prop="resourceTitle">
                    <el-input v-model="addForm.resourceTitle"></el-input>
                </el-form-item>
                <el-form-item label="描述：" prop="resourceDescribe">
                    <el-input v-model="addForm.resourceDescribe"></el-input>
                </el-form-item>

                <el-form-item label="上传：">
                    <my-upload buttonName="选择文件上传" @selectedFile="selectedFile"></my-upload>
                    <el-tag :type="file.type">{{file.fileName}}</el-tag>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addSubmit">确认新增</el-button>
            </div>
        </el-dialog>
        <!--新增界面-->

        <!--编辑界面-->
        <el-dialog title="更新资料" v-model="editFormVisible" :close-on-click-modal="false">

            <el-form :model="editForm" label-width="100px" ref="editForm" :rules="addRules">
                <el-form-item label="标题：" prop="resourceTitle">
                    <el-input v-model="editForm.resourceTitle"></el-input>
                </el-form-item>
                <el-form-item label="描述：" prop="resourceDescribe">
                    <el-input v-model="editForm.resourceDescribe"></el-input>
                </el-form-item>

                <el-form-item label="上传：">
                    <my-upload buttonName="选择文件上传" @selectedFile="selectedFile"></my-upload>
                    <el-tag :type="file.type">{{file.fileName}}</el-tag>
                    <el-tag type="success">注意：如上传将会覆盖已经存在的文件资料</el-tag>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click.native="editFormVisible = false">取消</el-button>
                <el-button type="primary" @click="editSubmit" :loading="editLoading">确认更新</el-button>
            </div>
        </el-dialog>
        <!--编辑-->

        <div style="width:100%;height:10px;"></div>

        <!--分页-->
        <div class="block" style="margin-left:15%">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page="currentPage" :page-sizes="[15, 20, 25, 30]" :page-size="pageSize"
                           layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>

    </div>
</template>

<script>
    //获取所有资源信息                                              -根据id查资源的详情
    import {selectStudyResource, addResource,delresource,downloadFromNginx,updateResource, queryResById} from '../../api/api';
    import myUpload from './public/myUpload.vue';
    export default {
        components: {myUpload},
        data() {
            return {
                tableData: [],

                //添加
                addFormVisible: false,//新增界面是否显示
                addLoading: false,
                editLoading:false,
                file: {
                    type: '',
                    fileName: '',
                    fileData: ''
                },

                //新增界面数据
                addForm: {
                    // course_id:'',
                    //资料名称，资料标题，资料描述
                    resourceName: '',
                    resourceTitle: '',
                    resourceDescribe: '',
                },
                addRules: {
                    resourceTitle: [{required: true, message: '资料标题必须填写', trigger: 'blur'}],
                    resourceDescribe: [{required: true, message: '描述必须填写', trigger: 'blur'}]
                },
                //分页
                total: 0,//列表总条数
                pageSize: 15,//每页条数
                currentPage: 1,//当前页码
                listLoading: false,
                sels: [], //列表选中咧
                //教师id 课程id
                teacherid: 1,
                courseid: 1,

                editFormVisible: false,//编辑界面是否显示
                //编辑 -------------------------------------------------------------------》》》》
                editForm: {
//                    resourceId: '',
//                    resourceName: '',
//                    resourceTitle: '',
//                    resourceDescribe: ''
                },

            }
        },
        mounted() {
            this.getdata();
        },
        methods: {
            selsChange: function (sels) {
                this.sels = sels;
            },
            //添加导学资源 点击方法
            resourceAdd() {
                this.addFormVisible = true;
                this.file.type = "primary";
                this.file.fileName = "未选择任何文件";
                this.addForm = {
                    course_id: '1',
                    //资料名称，资料标题，资料描述   默认值
                    resourceName: '',
                    resourceTitle: '',
                    resourceDescribe: ''

                };
            },
            //新增方法
            addSubmit: function () {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        if (this.file.fileData != '') {
                            this.$confirm('确认提交吗？', '提示', {}).then(() => {
                                this.addLoading = true;
                                let formData = new FormData();
                                formData.append("resourceFile", this.file.fileData);
                                formData.append("resourceTitle", this.addForm.resourceTitle);
                                formData.append("resourceDescribe", this.addForm.resourceDescribe);

                                addResource(formData).then((res) => {
                                    this.addLoading = false;
                                    let {resCode} = res;
                                    if (resCode != 0) {
                                        this.$message({
                                            message: '保存失败',
                                            type: 'error'
                                        });

                                    } else {
                                        this.$message({
                                            message: '提交成功',
                                            type: 'success'
                                        });
                                        this.file.fileData='';
                                        this.$refs['addForm'].resetFields(); //重置 字段
                                        this.addFormVisible = false;
                                        this.getdata();  //获取页面数据
                                    }

                                });
                            });
                        }

                    }
                });
            },

            /**
             * 下载
             * */
            downResource(id){
                let param={resourceId:id};
                queryResById(param).then(res=>{
                   if(res.resCode==0){
                       downloadFromNginx(res.resData.resourceName,res.resData.resourcePath);
                   }
                });
            },

            // 删除操作 index下标 从0开始，    row 元素  方法
            handleDelete(index, row) {
                this.$confirm('确认删除？', '提示', {}).then(()=>{
                    let para = {
                        resourceId: row.resourceId
                    };
                    this.listLoading = true;
                    delresource(para).then((res) => {
                        if (res.resCode==0){
                            this.$message({
                                message: '删除操作成功',
                                type: 'success'
                            });
                           this.tableData.splice(index,1);//删除成功，移除表格数据，无需请求一遍数据库
                        } else{
                            this.$message({
                                message: '删除操作失败',
                                type: 'error'
                            });
                        }
                        this.listLoading = false;
                    })
                });
            },

            // 自定义方法，从数据库取值方法
            getdata() {
                let para = {
                    pageSize: this.pageSize,
                    pageNum: this.currentPage
                };

                this.listLoading = true;
                selectStudyResource(para).then((res) => {
                    if (res.resCode == 0) {
                        this.tableData = res.resData.list;
                        this.total = res.resData.total;
                    }
                    this.listLoading = false;
                });

            },

            /**
             * 选取的文件 参数为文件句柄
             */
            selectedFile(file){
                this.file.fileName = file.name;
                this.file.type = "success";
                this.file.fileData = file;
                //console.log(file);
            },

            //分页件 ---------------------------------------------------------------------------------------------
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageSize = val;
                this.getdata();
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.currentPage = val;
                this.getdata();
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.editFormVisible = true;
                Object.assign(this.editForm,row);//将行信息带入编辑界面
                this.file.type = "primary";
                this.file.fileName = "未选择任何文件";
            },

            /**
             * 更新资料操作
             */
            editSubmit() {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            let formData = new FormData();

                            if (this.file.fileData != ''){
                                formData.append("resourceFile", this.file.fileData);
                            }
                            formData.append("resourceTitle", this.editForm.resourceTitle);
                            formData.append("resourceDescribe", this.editForm.resourceDescribe);
                            formData.append("resourcePath", this.editForm.resourcePath);
                            formData.append("resourceId", this.editForm.resourceId);
                            updateResource(formData).then((res) => {
                                this.editLoading = false;
                                this.editFormVisible = false;
                                if (res.resCode==0){
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                    this.getdata();
                                    this.$refs['editForm'].resetFields();
                                }
                                else{
                                    this.$message({
                                        message: '服务器出现异常，提交失败',
                                        type: 'error'
                                    });
                                }
                            });
                        });
                    }
                });
            },


        }
    }
</script>